package com.example.b_308.myapplication.comment.base;

/**
 * Created by tongkang  on 2017/6/9.
 * 监听类
 */


import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MultiListeners<T> {
    /**
     * 弱引用集合
     */
    private List<WeakReference<T>> a = new ArrayList();

    /**
     * 构造方法
     */
    public MultiListeners() {
    }

    /**
     * 添加监听
     *
     * @param listener
     */
    public void addListener(T listener) {
        //添加监听
        this.a.add(new WeakReference(listener));
    }

    /**
     * 清空所有监听
     */
    public void removeAll() {
        a.clear();
    }

    /**
     * 移除监听
     *
     * @param listener
     */
    public void removeListener(T listener) {
        for (int i = this.a.size() - 1; i >= 0; --i) {
            WeakReference ref = (WeakReference) this.a.get(i);
            if (ref.get() != null && ref.get() == listener) {
                this.a.remove(i);
                break;
            }
        }

    }

    /**
     * 监听动作
     *
     * @param action
     */
    public void listenersDoAction(IListenerAction<T> action) {
        ArrayList copyListeners = new ArrayList(this.a);
        Iterator var3 = copyListeners.iterator();
        //循环迭代 做动作
        while (var3.hasNext()) {
            WeakReference<T> wr = (WeakReference) var3.next();
            if (wr != null && wr.get() != null) {
                action.run(wr.get());
            }
        }
    }

    /**
     * 监听动作接口
     *
     * @param <T>
     */
    public interface IListenerAction<T> {
        void run(T var1);
    }
}
